package com.byCreation.Profile;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.byCreatetion.adabter.CompareAdapter;
import com.byCreation.Control.Control;
import com.byCreation.t_globe.R;
import com.demo.t_globe.chart.SpiderWebChart;
import com.demo.t_globe.chart.TitleValueEntity;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;




import Myclass.ConnectInternet;
import Parser.HttpGetJson;
import android.R.integer;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class CompareActivity extends Activity implements OnClickListener{

	private CompareAdapter imageAdapter; 
	private ImageView image; 
	
	 
	 
	// ==================ListView======================
			private Gallery gallery;
			private CompareAdapter adapter;
			public static ArrayList<HashMap<String, Object>> MyArrList;
			private HashMap<String, Object> map = new HashMap<String, Object>();
			private ProgressDialog mProgressDialog;

			
			private String[] id_detail={"Lah Own Khaolak Resort","Ocean Breeze Resort","Green Beach Resort","Ocean Breeze Resort"};
			private String[] id_title={"Khao Lak -- 25 Years of Friendship","Transfer from Phuket Airport to Khao Lak", "Khao Lak Center in Khao Lak, Phang Nga","Health Services in Ban Bang Niang" ,"A History of Khao Lak -- 25 Years of Friendship" ,"Dive Schools and Dive Shops in Khao Lak Center" ,"Health Services and Massage in Khao Lak Center" ,"Money Services in Khao Lak Center" };
			
		
			// ===============GoogleAnalytics==============
			private GoogleAnalytics mGaInstance;
			private Tracker mGaTracker;
			// =============================================
// ===================================googleAnalytics=============================
		@Override
		public void onStart() {
			super.onStart();
			// The rest of your onStart() code.
			EasyTracker.getInstance().activityStart(this); // Add this method.
			mGaTracker.sendView("Compare Screen");

		}

		@Override
		public void onStop() {
			super.onStop();
			// The rest of your onStop() code.
			EasyTracker.getInstance().activityStop(this); // Add this method.

		}

		// ================================================================================	
			
			
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_compare);
		
		
		// =============================GoogleAnalytics=========================
		mGaInstance = GoogleAnalytics.getInstance(this);
		mGaTracker = mGaInstance.getTracker(Control.IDGoogleanalytics);		
		
		
		
		initSpiderWebChart();
		
		
		final ImageView img_close = (ImageView) findViewById(R.id.img_close);
		 img_close.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Perform action on click   
           	 finish();
              
            }
        });
		 
		
		 
	
		if(new ConnectInternet(CompareActivity.this).checkInternetConnection())
		new LoadData().execute();
		
		 
	}
	
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	    super.onConfigurationChanged(newConfig);

	    // Checks the orientation of the screen
	    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
	        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
	    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
	        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
	    }
	}
	
	//==Chart
	private SpiderWebChart spiderwebchart1; 
	
    
	
	private void initSpiderWebChart()
    {
		

    	factory = LayoutInflater.from(CompareActivity.this);
		myView = factory.inflate(R.layout.item_spider, null);
		layout = (ViewGroup)findViewById(R.id.lay_graph);
	    spiderwebchart1 = (SpiderWebChart)myView.findViewById(R.id.spiderwebchart1);
         
    }
	
	
	private LayoutInflater factory;
	private View myView;
	private ViewGroup layout;
	
	
	
	
	
	private void SetListView()
   {
	
		  
	
				
				
			
			
			gallery.setOnItemSelectedListener( new OnItemSelectedListener() {
			    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
	        		
			    	Log.e("TG","setOnItemSelectedListener");
	            	layout.removeAllViews();
	            	factory=null;
	            	myView=null;
	            	layout=null;
	            	spiderwebchart1=null;
	            	
	            	factory = LayoutInflater.from(CompareActivity.this);
	        		myView = factory.inflate(R.layout.item_spider, null);
	        		layout = (ViewGroup)findViewById(R.id.lay_graph);
	        	    spiderwebchart1 = (SpiderWebChart)myView.findViewById(R.id.spiderwebchart1);
	            	

	            		List<TitleValueEntity> data1 = new ArrayList<TitleValueEntity>();
	        		
	        		try {data1.add(new TitleValueEntity("Quality ", Integer.parseInt(MyArrList.get(position).get("rating1").toString())));} catch (Exception e) {data1.add(new TitleValueEntity("Service ",0));}
	        		try {data1.add(new TitleValueEntity("Location ", Integer.parseInt(MyArrList.get(position).get("rating2").toString())));} catch (Exception e) {data1.add(new TitleValueEntity("Clean ",0));}
	        		try {data1.add(new TitleValueEntity("Beauty ", Integer.parseInt(MyArrList.get(position).get("rating3").toString())));} catch (Exception e) {data1.add(new TitleValueEntity("Facilites ",0));}
	        		try {data1.add(new TitleValueEntity("Money ", Integer.parseInt(MyArrList.get(position).get("rating4").toString())));} catch (Exception e) {data1.add(new TitleValueEntity("Location ",0));}
	        		try {data1.add(new TitleValueEntity("Green ", Integer.parseInt(MyArrList.get(position).get("rating5").toString())));} catch (Exception e) {data1.add(new TitleValueEntity("Price ",0));}
	        		
	        		
			    	Log.e("TG","1:"+MyArrList.get(position).get("rating1").toString());
			    	Log.e("TG","2:"+MyArrList.get(position).get("rating2").toString());
			    	Log.e("TG","3:"+MyArrList.get(position).get("rating3").toString());
			    	Log.e("TG","4:"+MyArrList.get(position).get("rating4").toString());
			    	Log.e("TG","5:"+MyArrList.get(position).get("rating5").toString());

	        		

	        		List<List<TitleValueEntity>> data_value1 = new ArrayList<List<TitleValueEntity>>();
	        		data_value1.add(data1);
	        	
	        		
	        		spiderwebchart1.setData(data_value1);
	        		spiderwebchart1.setLatitudeNum(5);
	        		
	        		
	        		myView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
	        		layout.addView(myView);
			    
			    
			    
			    }

			    public void onNothingSelected(AdapterView<?> arg0) {
			        // TODO Auto-generated method stub
			    }
			});
			
		
   }

	

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}
	
	
	
	class LoadData extends AsyncTask<Object, Integer, Object> {

		boolean Cancelled=false;
		
		
		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub]
			Cancelled=true;
			super.onCancelled();
		}

		@SuppressWarnings("null")
		@Override
		protected Object doInBackground(Object... params) {

					 
				 
				 try {
						
						JSONObject jsonObj=null;
						jsonObj = new JSONObject(HttpGetJson.GetJson(Control.getAPI_Mycompare(Control.UserName),Control.user,Control.pass));
						JSONArray jsonarray_data=jsonObj.getJSONArray("compare");
							
						
						 for (int i = 0; i <jsonarray_data.length(); i++)
						 { 
							 
							 map = new HashMap<String, Object>();
							 JSONObject jsonObj_data=jsonarray_data.getJSONObject(i);

							 map.put("pageid",jsonObj_data.getString("cardid"));
							 map.put("title",jsonObj_data.getString("cardname"));
							// map.put("detail",jsonObj_data.getString("name"));
							 map.put("img",jsonObj_data.getString("img"));
							
							
							 
							 
								
							try {map.put("rating1",jsonObj_data.getString("rating1"));} catch (Exception e) {}
							try {map.put("rating2",jsonObj_data.getString("rating2"));} catch (Exception e) {}
							try { map.put("rating3",jsonObj_data.getString("rating3"));} catch (Exception e) {}
							try {map.put("rating4",jsonObj_data.getString("rating4"));} catch (Exception e) {}
							
							int sum=0;
							try { sum=(Integer.parseInt(jsonObj_data.getString("rating5"))+Integer.parseInt(jsonObj_data.getString("rating1"))+Integer.parseInt(jsonObj_data.getString("rating2"))+Integer.parseInt(jsonObj_data.getString("rating3"))+Integer.parseInt(jsonObj_data.getString("rating4")))/5;} catch (Exception e) {};
							 
							
							try { map.put("rating5",jsonObj_data.getString("rating5"));} catch (Exception e) {map.put("rating5","0");};
							try { map.put("rating_sum",""+sum);} catch (Exception e) {map.put("rating_sum","0");};

							 
							
							Log.e("TG","rating1:"+jsonObj_data.getString("rating1"));
							Log.e("TG","rating2:"+jsonObj_data.getString("rating2"));
							Log.e("TG","rating3:"+jsonObj_data.getString("rating3"));
							Log.e("TG","rating4:"+jsonObj_data.getString("rating4"));
							Log.e("TG","rating5:"+jsonObj_data.getString("rating5"));

							
							
						     MyArrList.add(map);
						 }
						
						
						 
						 
					} catch (final JSONException e) {
						// TODO Auto-generated catch block
						runOnUiThread(new Runnable() {
						    public void run() {
						       Toast.makeText(CompareActivity.this,e.getMessage(),2000).show();
						    }
						});
						
						e.printStackTrace();
					}
				 
				 
				 
			return null;
		}

		@Override
		protected void onPreExecute() {

			   gallery = (Gallery)findViewById(R.id.galleryView);
				CompareActivity.this.setProgressBarIndeterminateVisibility(true);
				
				
				 //=====================ProgressDialog==========================
		        mProgressDialog = new ProgressDialog(CompareActivity.this);
		        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);         
		        mProgressDialog.setMessage("Loading......");                       
		        mProgressDialog.setCancelable(false);  
		        mProgressDialog.show();
			
		
				MyArrList = new ArrayList<HashMap<String, Object>>();

				
				
				
			adapter=null;
			
			if (adapter == null) {
				adapter = new CompareAdapter(CompareActivity.this, MyArrList);
				gallery.setAdapter(adapter);
				
				Log.e("TG", "adapter = new NotiListAdapter(getActivity(), MyArrList);");
				
			}

			
			super.onPreExecute();
		}

		@Override
		public void onProgressUpdate(Integer... progress) {

			Log.e("star", "progressupdate");
			
			
		}

		@Override
		protected void onPostExecute(Object result) {
		
			if(!Cancelled)
			{
				runOnUiThread (new Thread(new Runnable() { 
		         public void run() {
		                adapter.notifyDataSetChanged();      
		                

						Log.e("TG", " adapter.notifyDataSetChanged();  ");
		         }
		     	}));
			}
			
			
			if(mProgressDialog!=null)
				mProgressDialog.dismiss();
			
			SetListView();
			
		}

	}


	
	

}
